package com.leyou.cart.web;

import com.leyou.cart.entity.Cart;
import com.leyou.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @package com.leyou.cart.web
 * @description: 购物车控制层
 * @author: 许超越
 * @date 2019/7/10 21:01
 * @version: V1.0
 */
@RestController
@RequestMapping
public class CartController {

    @Autowired
    private CartService cartService;


    /**
     * 购物车添加商品
     * @param cart
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> addCart(@RequestBody Cart cart) {
        cartService.addCart(cart);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    /**
     * 查询用户的购物车
     * @return
     */
    @GetMapping("list")
    public ResponseEntity<List<Cart>> queryCartList() {
        List<Cart> carts = cartService.queryCartList();
        if (carts == null) {
            //购物车没有返回404
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        //购物车查询到返回200
        return ResponseEntity.ok(carts);
    }


    /**
     * 修改购物车商品的数量
     * @param skuId 商品id
     * @param num 修改后的商品数量
     * @return
     */
    @PutMapping
    public ResponseEntity<Void> updateCartNum(@RequestParam("id") Long skuId, @RequestParam("num") Integer num) {
        cartService.updateCartNum(skuId, num);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 删除购物车商品
     * @param skuId 商品的id
     * @return
     */
    @DeleteMapping("{skuId}")
    public ResponseEntity<Void> deleteCart(@PathVariable("skuId") String skuId) {
        cartService.deleteCart(skuId);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 批量新增未登入添加的购物车商品
     * @param cartList
     * @return
     */
    @PostMapping("list")
    public ResponseEntity<Void> addCartList(@RequestBody List<Cart> cartList) {
        cartService.addCartList(cartList);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
